package com.example.curd.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.curd.common.ResponseHelper;
import com.example.curd.common.ResponseModel;
import com.example.curd.entity.User;
import com.example.curd.mapper.UserMapper;
import com.example.curd.payload.base.PageRequest;
import com.example.curd.payload.request.User.AddUserRequest;
import com.example.curd.payload.request.User.DeleteUserRequest;
import com.example.curd.payload.request.User.SelectUserRequest;
import com.example.curd.payload.request.User.UpdateUserRequest;
import com.example.curd.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dakai
 * @since 2021-04-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
  @Resource
  private UserMapper userMapper;

  @Override
  public IPage<User> selectUser(SelectUserRequest request) {
    IPage<User> UserIPage = userMapper.selectUser(PageRequest.getPage(request), request.getUsername());
    return UserIPage;
  }

  @Override
  public ResponseModel addUser(AddUserRequest request) {
    User user = new User();
    //判断用户名是否存在
    Integer count = userMapper.isHaveUser(request.getUsername());
    if (count != 0) {
      return ResponseHelper.error("用户已存在");
    }
    user.setUsername(request.getUsername())
      .setPassword(request.getPassword())
      .setId(request.getId());
    this.save(user);
    return ResponseHelper.buildResponseModel("添加成功");
  }

  @Override
  public void updateUser(UpdateUserRequest request) {
    User user = this.getById(Long.valueOf(request.getId()));
    BeanUtils.copyProperties(request, user);
    this.updateById(user);
  }

  @Override
  public void deleteUser(DeleteUserRequest request) {
    userMapper.deleteUser(request.getId());
  }
}

